package com.iot.ic.modules.web;

import com.alibaba.fastjson.JSONObject;
import com.iot.ic.common.web.BaseController;
import com.iot.ic.modules.model.PatientCase;
import com.iot.ic.modules.model.Trade;
import com.iot.ic.modules.model.User;
import com.iot.ic.modules.service.PatientCaseService;
import com.iot.ic.modules.service.TradeService;
import com.iot.ic.modules.service.UserService;
import com.iot.ic.modules.util.MiPushUtils;
import com.xiaomi.xmpush.server.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/case")
public class PatientCaseController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private PatientCaseService patientCaseService;
	@Autowired
	private TradeService tradeService;

	@RequestMapping("/saveCase")
	@ResponseBody
	public Map<String, Object> saveCase(HttpServletRequest request, Integer id, Integer userId, Integer drId,
			Integer tradeId) {
		if (StringUtils.isEmpty(userId)) {
			return packInfo(false, "userId为空，保存", "userId");
		}
		if (drId == null) {
			return packInfo(false, "尚未选择医生，保存", "drId");
		}

		if (tradeId == null) {
			return packInfo(false, "参数为空", "tradeId");
		}

		PatientCase pc = new PatientCase();
		pc.setAddtime(new Date());
		try {
			User user = userService.findById(userId, 0);
			User drUser = userService.findById(drId, 1);
			List<Trade> trades = tradeService.findTrade(tradeId, null, null);
			if (user == null) {
				return packInfo(false, "用户不存在，保存");
			}
			if (drUser == null) {
				return packInfo(false, "医生不存在，保存");
			}
			if (trades == null || trades.size() == 0) {
				return packInfo(false, "订单不存在");
			}
			String picUrl = savePic(user, request);
			if (picUrl == null) {
				return packInfo(false, "图片上传失败，保存");
			}
			if (id != null) {
				pc.setId(id);
			}
			pc.setUser(user);
			pc.setTradeId(tradeId);
			pc.setDrUser(drUser);
			pc.setType(0);
			pc.setPicUrls(picUrl);
			PatientCase patient = patientCaseService.saveOrUpdateObject(pc);
			String description = patient.getUser().getTrueName() + "病人请求你对其病情做诊断";
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("patientCase", patient);
			map.put("messagePayload", description);
			map.put("userAccount", patient.getDrUser().getMobile());
			JSONObject jo = new JSONObject(map);
			String content = jo.toJSONString();
			Result pushResult = MiPushUtils.send(content, "病人请求", description, patient.getDrUser().readmRegId());
			System.out.println("MessageId: " + pushResult.getMessageId() + "\n ErrorCode: "
					+ pushResult.getErrorCode().getDescription() + "\n Reason: " + pushResult.getReason());
			Map<String, Object> result = packSaveInfo(patient);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * 保存图片
	 *
	 * @param user
	 * @param request
	 */
	private String savePic(User user, HttpServletRequest request) throws Exception {
		List<String> picList = springUpload(request, user.getTrueName(), "caseImg");
		if (picList == null || picList.size() == 0) {
			return null;
		}
		String picUrl = "";
		for (int i = 0; i < picList.size(); i++) {
			picUrl = picUrl + picList.get(i) + ",";
		}
		picUrl = picUrl.substring(0, picUrl.lastIndexOf(","));
		return picUrl;
	}

	/**
	 * diagno 诊断病例 评级
	 *
	 * @return json
	 */
	@RequestMapping("/diagno")
	@ResponseBody
	public Map<String, Object> diagnoCase(Integer id, Integer drId, String caseLeave, String diagnoNote) {
		if (StringUtils.isEmpty(id)) {
			return packInfo(false, "案例编号为空，保存", "id");
		}
		if (StringUtils.isEmpty(drId)) {
			return packInfo(false, "医生编号为空，保存", "drId");
		}
		if (StringUtils.isEmpty(caseLeave) || !"abcd".contains(caseLeave)) {
			return packInfo(false, "病情级别错误，保存", "caseLeave");
		}
		// if (StringUtils.isEmpty(diagnoNote)) {
		// return packInfo(false, "请做简单的评语，保存", "diagnoNote");
		// }
		try {
			PatientCase patient = patientCaseService.diagnoCase(id, drId, caseLeave, diagnoNote);
			String description = patient.getDrUser().getTrueName() + "医生已对你的病情做出总结，" + patient.getCaseNote();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("patientCase", patient);
			map.put("messagePayload", description);
			map.put("userAccount", patient.getUser().getMobile());
			JSONObject jo = new JSONObject(map);
			String content = jo.toJSONString();
			Result result = MiPushUtils.send(content, "诊断结果", description, patient.getUser().readmRegId());
			System.out.println("MessageId: " + result.getMessageId() + "\n ErrorCode: "
					+ result.getErrorCode().getDescription() + "\n Reason: " + result.getReason());
			return packSaveInfo(patient);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	/**
	 * diagno 查询
	 *
	 * @return json
	 */
	@RequestMapping("/findCase")
	@ResponseBody
	public Map<String, Object> findCase(Integer id, Integer userId, Integer drId, String caseLevel, Integer type) {
		try {
			List<PatientCase> patient = patientCaseService.findCase(id, userId, drId, caseLevel, type);
			return packData(patient);
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}
}
